/* Copyright (c) 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package openbang.account.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import openbang.account.service.entity.Group;
import openbang.account.service.entity.MediaObject;
import openbang.account.service.entity.UserAccount;
import openbang.account.service.util.PMF;
import openbang.account.service.util.SessionHelper;
import openbang.account.service.vo.BusinessEnum;
import openbang.account.service.vo.GroupTypeEnum;
import openbang.account.service.vo.UserLoginInfo;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

/**
 * 图片保存操作 --- 需要付费！！！
 * upload.jsp 提交给  GAE服务处理
 * 转交给该Servlet 进行相关业务数据处理
 * 
 * You must have billing enabled in order to use the Blobstore API in apps you deploy to the App Engine environment. 
 * When your app is running locally in the development server, you can use the Blobstore API freely.
 * 
 * @author aibozeng
 *
 */

@SuppressWarnings("serial")
public class UploadPostServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(UploadPostServlet.class.getName());
  private BlobstoreService blobstoreService = 
    BlobstoreServiceFactory.getBlobstoreService();
  private AccountServiceImpl accountService = new AccountServiceImpl();
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
      IOException {

	// 从 GAE 图片服务器取出已经上传的图片对象
    Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
    if (blobs.keySet().isEmpty()) {
    	SessionHelper.forwardToErrorPage(BusinessEnum.UPLOAD_FACEPHOTO.getDesc(),"上传文件为空,或超出1 兆字节限制","请重新上传", req, resp);
    	return;
    }

    Iterator<String> names = blobs.keySet().iterator();
    String blobName = names.next();
    BlobKey blobKey = blobs.get(blobName);
    String blobKeyStr = blobKey.getKeyString();

    //如果没有登录,删除已上传的图片
    UserLoginInfo userLoginInfo = SessionHelper.getUserLoginInfo(req);
	if(!userLoginInfo.isLogined()){
	    blobstoreService.delete(blobKey);
	    log.warning("有黑客? 没有登录时访问 url="+req.getRequestURL().toString());
		SessionHelper.forwardToErrorPage(BusinessEnum.UPLOAD_FACEPHOTO.getDesc(),"没有登录","请重新登录", req, resp); 
		return;
    }		

	//取出上传的所有参数
    BlobInfoFactory blobInfoFactory = new BlobInfoFactory();
    BlobInfo blobInfo = blobInfoFactory.loadBlobInfo(blobKey);

    String contentType = blobInfo.getContentType();
    long size = blobInfo.getSize();
    Date creation = blobInfo.getCreation();
    String fileName = blobInfo.getFilename();
    if(fileName!=null){
    	fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
    }

    String title = req.getParameter("title");
    if(title!=null){
    	title = new String(title.getBytes("ISO-8859-1"),"UTF-8");
    }
    String description = req.getParameter("description");
    if(description!=null){
    	description = new String(description.getBytes("ISO-8859-1"),"UTF-8");
    }   
    String businessType = req.getParameter("businessType");
    //boolean isShared = true;
    //保存相关信息到业务数据库，除了图片内容
	PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
    	//放到一个缺省的组中
    	Group group = accountService.findGroup(userLoginInfo.getId(), GroupTypeEnum.MEDIA.getCode(), Group.DefaultFacePhoto, pm);
    	if(group==null){
    		group = new Group();
    		//group.setCreation(new Date());
    		group.setDescription("放置头像的组(系统创建)");
    		group.setGroupType(GroupTypeEnum.MEDIA.getCode());
    		group.setTitle(Group.DefaultFacePhoto);
    		//group.setUpdTime(new )
    		group.setUserId(userLoginInfo.getId());
    		pm.makePersistent(group);
    	}
    	
    	MediaObject mediaObj = new MediaObject();
    	mediaObj.setBlobKey(blobKeyStr);
    	mediaObj.setContentType(contentType);
    	mediaObj.setCreation(creation);
    	mediaObj.setDescription(description);
    	mediaObj.setFileName(fileName);
    	mediaObj.setGroup(group);
    	mediaObj.setGroupId(group.getId());
    	mediaObj.setPublic(true);
    	mediaObj.setSize(size);
    	mediaObj.setTitle(title);
    	mediaObj.setUserId(userLoginInfo.getId());
    	
        // 使用 getWidth()会得到 ：java.lang.UnsupportedOperationException: No image data is available.
    	//ImagesService imagesService = ImagesServiceFactory.getImagesService();
        //Image image = ImagesServiceFactory.makeImageFromBlob(blobKey);
    	//mediaObj.setWidth(image.getWidth());
    	//mediaObj.setHeight(image.getHeight());
    	pm.makePersistent(mediaObj);
    	
    	//更新 UserAccount
    	UserAccount userAccount = pm.getObjectById(UserAccount.class,userLoginInfo.getId());
    	userAccount.setFacePhotoId(mediaObj.getId());
    	String photoUrl = "/displayPhoto.do?outputType=html&blobKey="+blobKeyStr+"&businessType="+businessType;
    	userAccount.setFacePhotoUrl(photoUrl);
    	pm.close();

    	//SEVERE: Must only return a redirect from a Blobstore upload callback.
		//displayPhoto.jsp 需要的其他参数
    	//req.setAttribute("mediaObject",mediaObj);
    	//req.setAttribute("businessType",businessType);
		//RequestDispatcher dispatcher = req
		//		.getRequestDispatcher("WEB-INF/jsp/displayPhotoParam.jsp");
		//dispatcher.forward(req, resp);
        log.warning("end upload ok fileName="+mediaObj.getFileName()+",title="+title);
        //log.warning(new String(title.getBytes("ISO-8859-1"),"UTF-8"));
        //log.warning(new String(title.getBytes("ISO-8859-1"),"GBK"));
        //log.warning(new String(title.getBytes("GBK"),"UTF-8"));
    	resp.sendRedirect(photoUrl);
    } catch (Exception e) {      
        blobstoreService.delete(blobKey);
        //Must only return a redirect from a Blobstore upload callback.
		SessionHelper.forwardToErrorPage(BusinessEnum.UPLOAD_FACEPHOTO.getDesc(),"保存数据失败","请重新登录后，再上传", req, resp); 
    }finally{
    	if(!pm.isClosed())
    	  pm.close();
    }
  }
}
